import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    goodsListData: [],
    totalGoods: 0,
    goBuyGoodsListData: [],
    // 地址管理列表
    addressList: [
      {
        id: "1",
        name: "张三",
        tel: "13000000000",
        address: "浙江省杭州市西湖区文三路 138 号东方通信大厦 7 楼 501 室"
      },
      {
        id: '2',
        name: '李四',
        tel: '1330400000',
        address: '浙江省杭州市拱墅区莫干山路 50 号'
      }
    ]
  },
  mutations: {
    //刷新商品总数
    calculateTotalGoods(state) {
      state.totalGoods = state.goodsListData.length
      // alert(state.totalGoods)
    },
    //添加商品
    addGoodsm(state, goodsDetail) {
      var test = state.goodsListData.some(item => {
        return item.id == goodsDetail.message.goods_id;
      });
      if (test) {
        state.goodsListData.forEach((item, index) => {
          if (item.id == goodsDetail.message.goods_id) {
            item.value += 1

          }
        });
      } else {
        state.goodsListData.push({
          id: goodsDetail.message.goods_id,
          price: goodsDetail.message.goods_price,
          title: goodsDetail.message.goods_name,
          thumb: goodsDetail.message.goods_small_logo,
          checked: true,
          value: 1
        })
      }
      //商品种类总数
      state.totalGoods = state.goodsListData.length
      //数据存入本地
      let json = JSON.stringify(state.goodsListData);
      localStorage.setItem("key", json);

    },
    //去买数据
    goBuy(state) {
      state.goBuyGoodsListData = []
      state.goodsListData.forEach(item => {
        if (item.checked) {
          state.goBuyGoodsListData.push(item)
        }
      })
    },
    editAddress(state, id) {
      const i = state.addressList.findIndex(item => item.id == id)
    },
    setAddress(state, info) {
      // console.log(info);
      let i = state.addressList.findIndex(item => item.id == info.id);
      // console.log(i);
      state.addressList[i].tel = info.tel;
      state.addressList[i].address = info.addressDetail;
      // console.log(state.addressList); 

    },
    addAddress(state, info) {
      console.log(info);
      let obj = {
        id: state.addressList.length++,
        name: info.name,
        tel: info.tel,
        address: info.addressDetail
      }
      state.addressList.push(obj)
    },
    //保存页面商品
    savePage(state) {
      let json = JSON.stringify(state.goodsListData);
      localStorage.setItem("key", json);
    },
    //刷新页面
    refreshPage(state) {

      let local = localStorage.getItem('key')
      state.goodsListData = JSON.parse(local)

    },
  },


  getters: {
    totalGoods: state => {
      return state.totalGoods
    }
  }
})
